package com.guchenbo.spring.boot.jdbc.origin;

import com.guchenbo.spring.boot.jdbc.UserDao;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * 纯jdbc编码方式的示例
 *
 * @Author guchenbo
 * @Date 2019/8/14.
 */
@Component
public class UserOriginDao implements UserDao {
    private static String url = "jdbc:mysql://127.0.0.1:3306/test";
    private static String user = "gcb";
    private static String password = "guchenbo";

    @Override
    public void insert() {
        try {
            Class.forName("com.mysql.jdbc.Driver");

            String sql = "insert into user(`name`, age) values ('jay', 12)";
            Connection conn = DriverManager.getConnection(url, user, password);
            // 设置为手动处理事务
            conn.setAutoCommit(false);

            Statement statement = conn.createStatement();
            statement.execute(sql);

            // 手动commit
            conn.commit();
            conn.close();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
